<?php
//============================================================================
// ____________________________PLIGG TEAM ADDON_______________________________
//
// This CLASS was created by AnAlienHolakres3 ||| XXXXX  XX     XX XXXX   XXXX
// (c) 2007-2008                Jakub Holasek ||| XXXXX  XX     XX X      X
// @last_update                    02/02/2008 ||| XX     XX     XX X  XX  X  XX
// @version                              0.12 ||| XX     XXXXXX XX XXXXX  XXXXX
//
// This file can be used by Pligg community.
//=============================================================================

// Class Team contains general information about teams

class Team {
    private $id   = 0;
    private $name = '';
    private $cat_id = 0;
    private $creator_id = '';
    private $setup_date = false;
    private $publicity = false;
    private $rating = 0;
    private $objective = '';
    private $last_modify = false;
    private $team_data;
    
    //related variables
    private $category_name = '';
    private $creator_name ='';


    //settings
    private $pagesize = 15;
    private $language = "cs"; // date format = 'year/day/month', other language date format - 'day.month.year'
    private $minimal_team_objective_length = 12;
    private $minimal_team_name_length = 3;
    //other 
    private $read = true;
    private $fullread = true;

    //============================================================================
    //  Function read_name() gets team name from database
    //============================================================================      
    function read_name() {
        global $db;

        $id=$this->id;

        if ($name=$db->get_var("SELECT team_name FROM " . table_teams . " WHERE team_id = $id")) {
            $this->name=$name;
            $this->read=true;
            return true;
            }

        $this->read=false;
        return false;
        }
    //============================================================================
    //  Function read_creator() gets team creator from database
    //============================================================================      
    function read_creator() {
        global $db;

        $id=$this->id;
                
        if ($cid=$db->get_var("SELECT team_creator_id FROM " . table_teams . " WHERE team_id = $id")) {
            $this->creator_id=$cid;
            $this->read=true;
            return true;
            }

        $this->read=false;
        return false;
        }   

        
    //============================================================================
    //  Function read_basic_dasta() gets team data (array) from database
    //============================================================================      
    function read_basic_data($offset) {
        global $db;
         
         $filter_by = $this->get_filter();
         $order_by = $this->get_sort();
          
          
         $ids=$db->get_results("SELECT team_id FROM " . table_teams . " $filter_by  $order_by LIMIT $offset, $this->pagesize");
          $id_count = count($ids);
       
       if ($ids) {
         foreach ($ids as $id) {
                                    
             if ($team_data[]=$db->get_results("SELECT team_id, team_name, category_name, team_objective, team_publicity, team_date,team_creator_id,user_login FROM " .                         table_teams . " 
             JOIN " . table_categories . " ON " . table_categories . ".category_id=" . table_teams . ".team_cat_id 
               JOIN " . table_users ." ON ". table_users . ".user_id=" . table_teams . ".team_creator_id WHERE team_id = $id->team_id")){
             } else {
            
             return false;
             }
             }
             $this->team_data = $team_data;
       
            return true;
       } return false;        
    }                  
               
    //============================================================================
    //  Function read(..) gets team data, if team data is cached it is used if not
    //  then data are get from database
    //============================================================================      

    function read($usecache = TRUE) {
        global $db, $cached_teams;

        $id=$this->id;

        if (isset($cached_teams[$id]) && $usecache == TRUE) { $team=$cached_teams[$id]; } else {
            //if this query changes, change it in team_summary.php
            $team             =$db->get_row("SELECT " . table_teams . ".*,category_name , user_login FROM " . table_teams . " 
            JOIN " . table_categories ." ON " . table_categories . ".category_id=" . table_teams . ".team_cat_id
            JOIN " . table_users ." ON ". table_users . ".user_id=" . table_teams . ".team_creator_id WHERE  team_id = $id");
            
            $cached_teams[$id]=$team;
            }

        if ($team) {
            $this->creator_id =    $team->team_creator_id;
            $this->creator_name = $team->user_login;
            $this->setup_date   = $this->get_date($team->team_date,null);
            $this->name         = $team->team_name;            
            $this->publicity    = $team->team_publicity;
            $this->last_modify  = $this->get_date($team->team_last_modify,'time');
            $this->rating       = $team->team_rating;
            $this->objective    = $team->team_objective;
            $this->cat_id       = $team->team_cat_id;
            $this->category_name = $team->category_name;

            return true;
            }

        $this->fullread=$this->read=false;
        return false;
        }
        
    //============================================================================
    //  Function read_id() gets team id from database by searching name
    //============================================================================      
    function read_id() {
        global $db;

        $name= $this->name;

        if ($id=$db->get_var("SELECT team_id FROM " . table_teams . " WHERE team_name = '$name'")) {
            $this->id=$id;
            $this->read=true;
            return true;
            }

        $this->read=false;
        return false;
        }

    //============================================================================
    //  Function store() saves team data in database
    //  @return true if storing was successfull otherwise false
    //============================================================================

    function store() {
        global $db;
                                        
        if (!$this->setup_date) $this->setup_date=time();

        $team_date       =$this->setup_date;
        $team_name       =$this->name;
        $team_creator    =$this->creator_id;
        $team_publicity  =$this->publicity;
        $team_last_modify=$this->last_modify;
        $team_rating     =$this->rating;
        $team_objective  =$this->objective;
        $team_cat_id     =$this->cat_id;
                                 
        if ($this->id === 0) {         
            $sql=("INSERT INTO " . table_teams
                           . " (team_date, team_name, team_creator_id, team_publicity, team_last_modify, team_rating, team_objective, team_cat_id)
            VALUES (FROM_UNIXTIME($team_date), '$team_name', $team_creator,$team_publicity, FROM_UNIXTIME($team_last_modify), $team_rating, '$team_objective', $team_cat_id)");
            
            } else {
            $sql="UPDATE " . table_teams
                . " set team_publicity = $team_publicity, team_last_modify = FROM_UNIXTIME($team_last_modify), team_rating = $team_rating, 
                team_objective = '$team_objective', team_cat_id = $team_cat_id
                WHERE team_id=$this->id";
            }

        if($db->query($sql)){         
            if ($this->id ===0) {
                
                    // we need to add to membership team creator
                    $this->read_id();  
                    $team_member = new Team_Member;
                    $team_member->set_team_id($this->id);
                    $team_member->set_user_id($team_creator);
                    
                    if ($team_member->store()){                              
                        return true;     
                    }
                
            } else {
             return true;   
            }
            
        }                       
          return false;
     }
         

    //============================================================================
    //  Function duplicate_name() finds out if team name is unique
    //  @return true if name is duplicate otherwise false    
    //============================================================================   

    function duplicate_name($team_name) {
        global $db;

        $team_name=$db->escape(strip_tags($team_name));
        $n        =$db->get_var("SELECT count(*) FROM " . table_teams . " WHERE team_name = '$team_name'");
        if ($n>0){
            return true;
        }   return false;
    }


    //============================================================================
    //  Function fill_print($mode) fills the smarty and shows the template 
    //  @param mode = full - when specific team is desired
    //  @param mode = basic - when team list is desired
    //============================================================================     
    function fill_print($mode) {
        global $main_smarty,$current_user;
                    
        if (!$this->read) { return; }                
        
           $main_smarty->assign('current_user_id', $current_user->user_id);                      
           $main_smarty->assign('current_user_name', $current_user->user_login);                      
           $main_smarty->assign('current_user_security_code',md5($current_user->user_login.$current_user->user_pass));
        
           $main_smarty->assign('minimal_team_objective_length',$this->minimal_team_objective_length);
           $main_smarty->assign('minimal_team_name_length',$this->minimal_team_name_length);  

        if ($mode == "full") {        
            
            $main_smarty->assign('team_url',my_pligg_base . '/team.php?id='.$_REQUEST['id']);
            $main_smarty->assign('team_objective', $this->objective);
            $main_smarty->assign('team_rating', $this->rating);
            $main_smarty->assign('team_rating_selected',1); 
            $main_smarty->assign('team_publicity', $this->publicity);
            $main_smarty->assign('team_publicity_select',1);
         
            $main_smarty->assign('team_id', $this->id);                                     
            $main_smarty->assign('creator_id', $this->creator_id);
            $main_smarty->assign('creator_name', $this->creator_name);
            
            $main_smarty->assign('creator_url',getmyurl('user2', $this->creator_name, 'profile'));                        
            $main_smarty->assign('creator_message_url',my_pligg_base . '/module.php?module=simple_messaging&view=compose&return=' . urlencode($_SERVER['REQUEST_URI']) .'&to=' .$this->creator_name);
            
            $main_smarty->assign('team_category_name', $this->category_name);
            $main_smarty->assign('team_category', $this->cat_id);
            $main_smarty->assign('team_name', $this->name);            
            $main_smarty->assign('team_date', $this->setup_date);            
            $main_smarty->assign('team_last_modify', $this->last_modify);                            
            
            }

        if ($mode == "basic") {                                           

            if ($this->team_data) {
                foreach ($this->team_data as $team_array) {
                    foreach ($team_array as $team) {
                        
                    $team_ids[] = $team->team_id;
                    $team_names[] = $team->team_name;
                    $team_category_names[] = $team->category_name;
                    $team_objectives[] = $team->team_objective;
                    $team_publicitys[] = $team->team_publicity;
                    $team_dates[] = $this->get_date($team->team_date,null);
                    $team_creator_ids[] = $team->team_creator_id;
                    $team_creator_names[] = $team->user_login;
                    $team_creator_urls[] = getmyurl('user2', $team->user_login, 'profile');
                    $team_creator_message_urls[] = my_pligg_base . '/module.php?module=simple_messaging&view=compose&return=' . 
                                                   urlencode($_SERVER['REQUEST_URI']) .'&to=' .$team->user_login;                                                   
                                                   
                    }   
                    
                    $main_smarty->assign('creator_ids', $team_creator_ids);
                    $main_smarty->assign('creator_names', $team_creator_names);            
                    $main_smarty->assign('creator_urls',$team_creator_urls);                        
                    $main_smarty->assign('creator_message_urls',$team_creator_message_urls);
                 
                    $main_smarty->assign('team_ids', $team_ids);
                    $main_smarty->assign('team_names', $team_names);
                    $main_smarty->assign('team_category_names', $team_category_names);
                    $main_smarty->assign('team_objectives', $team_objectives);
                    $main_smarty->assign('team_publicitys', $team_publicitys);
                    $main_smarty->assign('team_dates', $team_dates);
                }
            }
     
            
            }
        }
     //============================================================================
    //  Function delete_team() deletes team and its content, all members and tasks
    //  are deleted also (referential integrity)
    //============================================================================    
    
    function delete_team() {
       global $db;
       $id = $this->id;
       
       $sql = "DELETE FROM " . table_teams . " WHERE team_id=$id";
       
       if($db->query($sql)){                 
          return true;     
          
                }                 
          return false;
       
    
    }    
    //============================================================================
    //  Function team_exist() finds out if there is some team in database
    //  @return true if team exist, otherwise false
    //============================================================================      
    function team_exist() {
        global $db;
        
        $filter_by = $this->get_filter();
        $order_by = $this->get_sort();
               
        $exist=$db->get_var("SELECT team_id FROM " . table_teams . " $filter_by");


        if ($exist) { 
         return true; 
        }
        return false;
    }

    //========================================================================
    // Function check_team_access() checks if user is authorized for team 
    // access  - if user is team creator or team member
    // @return true if user can access team otherwise false
    //========================================================================    

    function check_team_access() {
         global $current_user;                 
                  
         $access=$this->get_publicity();
         
         if ($access == 1){
          return true;   
         } else { 
                   
          if ($this->is_team_member()){
           return true;
          }   
         }
          return false;
    }
     //========================================================================
    // Function is_team_member() returns true if user is team member    
    //========================================================================    
    function is_team_member() {
      global $current_user;
      
      $team_member = new Team_Member();
      $team_member->set_team_id($this->id);
       
          if ($team_member->check_member_id($current_user->user_id) || $this->is_team_creator()){
           return true;
          } 
           return false;
        
    }
    //========================================================================
    // Function refresh_team_modification() set new last modification date    
    //========================================================================      
 
    function refresh_team_modification($team_id) {
        global $db;
        $team_last_modify = time();        
        $db->query("UPDATE " . table_teams . " SET team_last_modify = FROM_UNIXTIME($team_last_modify) WHERE team_id=$team_id");
        
        
    }
    //========================================================================
    // Function user_is_not_team_creator($user_id) checks if desired user id is  
    // team creator id
    // @return true if user IS NOT team creator otherwise false 
    //======================================================================== 
    
    function user_is_not_team_creator($user_id) {
      $this->read_creator();
       $team_creator=$this->creator_id;
       
       if ($user_id != $team_creator) {
            return true;    
        }
            return false;   
    }
 
     //========================================================================
    // Function is_team_creator() checks if current user is team creator
    // @return true if user is team creator otherwise false
    //========================================================================    

    function is_team_creator() {
        global $current_user;
                               
         $this->read_creator();
          $team_creator = $this->creator_id;
        
        if ($current_user->user_id == $team_creator) {
            return true;    
        }
            return false;
    }   
                             
    //========================================================================
    // Function check_name_exist() checks team name if exists
    // @return true if name is correct otherwise false    
    //========================================================================    

    function check_name_exist() {
        if ($_POST["name"] == null) {
            
            return false;
            }             
            return true;
    }
    
    //========================================================================
    // Function check_name_length() checks name length
    // @return true if name length is correct otherwise false
    //========================================================================    

    function check_name_length() {
       
            if ($this->strlen_utf8(strip_tags(trim($_POST["name"]))) < $this->minimal_team_name_length) {  
                return false;
                }

            if ($this->strlen_utf8(strip_tags(trim($_POST["name"]))) > 30) {  
                header ('Location: ./attack.php?id=5');
                die;
                }
            
            return true;
        
     }

    //========================================================================
    // Function check_publicity() checks team accesibility
    // @return true if publicity is selected otherwise false    
    //========================================================================    

    function check_publicity() {        
        if ($_POST["publicity"] == null || $_POST["publicity"] == 999) {            
            return false;
            } else {                
            if (check_integer($_POST["publicity"])) {
                header ('Location: ./attack.php?id=3');
                die;
                }

            ;
            }

        return true;    
    }

    //========================================================================
    // Function check_category() checks team category
    // @return true if category is selected otherwise false
    //========================================================================    

    function check_category() {
        if ($_POST["category"] == null || $_POST["category"] == 999) {
            return false;
            } else {
            if (check_integer($_POST["category"])) {
                header ('Location: ./attack.php?id=4');
                die;
                }            
            }
        return true;
    }

    //========================================================================
    // Function check_objective_exist() checks team objective existence
    // @return true if objective exists otherwise false
    //========================================================================    

    function check_objective_exist() {
        if (!$_POST["objective"]) {            
            return false;
            }
            return true;            
    }
    //========================================================================
    // Function check_objective_length() checks team objective length
    // @return true if objective length is correct otherwise false
    //======================================================================== 
              
    function check_objective_length() {            
        if ($this->strlen_utf8(strip_tags(trim($_POST["objective"]))) < $this->minimal_team_objective_length) {                
            return false;
                }

        if ($this->strlen_utf8(strip_tags(trim($_POST["objective"]))) > 60) {
             header ('Location: ./attack.php?id=6');
              die;
                }            

        return true;
    }

    //========================================================================
    // Function check_rating() checks team rating
    // @return true if rating is selected
    // @return team_error number if it is incorrect    
    //========================================================================    

    function check_rating() {
        if ($_POST["rating"] == null || $_POST["rating"] == 999) {            
            return false;   
            } else {         
            if (check_integer($_POST["rating"])) {
                header ('Location: ./attack.php?id=7');
                die;
                }            
            }

        return true;
    }

    //========================================================================
    // Function check_sorting() checks team sorting
    // @return true if sorting is selected and it is correct
    // @return false otherwise
    //========================================================================   
    
    function check_sorting() { 
        if (isset($_GET['sortby'])){
         if (!ctype_digit(trim($_GET["sortby"]))) {              
                header ('Location: ./attack.php?id=10');
                die;
                }
          return true;                                                                                       
         }
          return false;
    }
    
    //========================================================================
    // Function check_filtering() checks team filtering
    // @return true if filtering is used and it is correct
    // @return false otherwise
    //========================================================================   
    
    function check_filtering() { 
         if (isset($_GET['filterby'])){
         if (!ctype_digit(trim($_GET["filterby"]))) {
                header ('Location: ./attack.php?id=9');
                die;
                }
         if ($_GET['filterby']!=999){ 
               return true;  
         }      
         }
          return false;
    }
    //========================================================================
    // Function check_id() checks team id
    // @return true if id is correct
    // @return false otherwise
    //========================================================================   
    
    function check_id($team_id) { 
         
         if (!ctype_digit(trim($team_id))) {    
                header ('Location: ./attack.php?id=1');
                die;
                }
        
          return true;
    }    
                
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
//  VARIABLE GET FUNCTIONS                                                                                                               X
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    //============================================================================
    //  Function get_team_count() returns count of teams in database,
    //  processing filtering and sorting
    //============================================================================      
    function get_team_count() {
        global $db;

        $filter_by = $this->get_filter();
        $order_by = $this->get_sort();
        
        $count=$db->get_var("SELECT count(team_id) FROM " . table_teams . " $filter_by");

        return $count;
        }



    //============================================================================
    //  Function get_date() returns date
    //  if language is set to "en" it returns date in Year/day/month format
    //  if any other language it returns date in day/month/year format
    //  @return date
    //============================================================================      
    function get_date($date,$mode) {
    if ($mode=='time') {    
     if ($this->language == "en") {
         $date = date('Y/d/m h:i a',strtotime($date));  
         
     } else {
         $date = date('d.m.Y H:i',strtotime($date));   
     }
    } else {
      if ($this->language == "en") {
         $date = date('Y/d/m',strtotime($date));  
         
     } else {
         $date = date('d.m.Y',strtotime($date));   
     }   
    } 
     
        return $date;           
    }
    
    //============================================================================
    //  Function get_language() returns team language
    //============================================================================      
    function get_language() {
     return $this->language;
    }
    
    //============================================================================
    //  Function get_id() returns team id
    //============================================================================      
    function get_id() {
     return $this->id; 
    }

    //============================================================================
    //  Function get_id() returns team id
    //============================================================================      
    function get_pagesize() { 
        return $this->pagesize; 
    }

    //============================================================================
    //  Function get_name() returns team name
    //============================================================================      
    function get_name() {
     return $this->name; 
    }
    
    //============================================================================
    //  Function get_sort() returns sort number if user selected some 
    //  sorting option sortby:
    //  1 = sorting by date ASC
    //  2 = sorting by date DESC (default)
    //  3 = sorting by name ASC
    //  4 = sorting by name DESC
    //  @return ORDER BY statement
    //============================================================================  
        
    function get_sort() {
        if ($this->check_sorting()){
            $sort=$_GET['sortby'];
        
            switch ($sort)
            {
            case 1 : 
            $order="ORDER BY team_name ASC";
            break;
            case 2 : 
            $order="ORDER BY team_name DESC";
            break;
            case 3 : 
            $order="ORDER BY team_date ASC";
            break;
            case 4 : 
            $order="ORDER BY team_date DESC";
        
            }                    
       } else {
       // nothing selected = ordering by team date DESC (newest) default
       $order = " ORDER BY team_date DESC";        
       }
       return $order;
    }
        
        
    //============================================================================
    //  Function get_filter() 
    // @return WHERE condition with specific category if user selected some
    // @return null if user does not select filter
    //============================================================================     
     
    function get_filter() {
     if ($this->check_filtering()){               
            
        $filter=$_GET['filterby'];
        $where = " WHERE team_cat_id=$filter ";        
        return $where;
            
        }
    }
    
    //============================================================================
    //  Function get_publicity()  returns team publicity    
    //============================================================================         
    function get_publicity() {
        return $this->publicity;
    }
    
        //============================================================================
    //  Function get_team_rating()  returns team rating
    //============================================================================         
    function get_team_rating() {
        return $this->rating;
    }
    
    //========================================================================
    // Function get_team_creator() returns team creator id
    //========================================================================    

    function get_team_creator() {
        global $current_user;
                
         $this->read_creator();
         return $this->creator_id;
    }  
        
        
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
//  VARIABLE SET FUNCTIONS                                                                                                               X
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


    //============================================================================
    //  Function set_id() sets team id
    //  @param team_id
    //============================================================================      
    function set_id($team_id) { 
        $this->id=$team_id; 
    }
    
    
    //============================================================================
    //  Function set_name() sets team name
    //  @param team_name
    //============================================================================      
    function set_name($team_name) {
        global $db;
     $this->name=htmlspecialchars($db->escape(strip_tags($team_name))); 
    }
    
    //============================================================================
    //  Function set_name() sets team name
    //  @param team_name
    //============================================================================      
    function set_publicity($team_publicity) {
     $this->publicity=$team_publicity;
    }
    
    //============================================================================
    //  Function set_category() sets team category
    //  @param team_category
    //============================================================================      
    function set_category($team_category) {
     $this->cat_id=$team_category;
    }
    
    //============================================================================
    //  Function set_objective() sets team objective
    //  @param team_objective
    //============================================================================      
    function set_objective($team_objective) {
        global $db;
     $this->objective= htmlspecialchars($db->escape(strip_tags($team_objective)));
    }
    
    //============================================================================
    //  Function set_rating() sets team rating
    //  @param team_rating
    //============================================================================      
    function set_rating($team_rating) {
     $this->rating=$team_rating;
    }
    
    //============================================================================
    //  Function set_creator() sets team creator
    //  @param team_creator
    //============================================================================      
    function set_creator($team_creator) {
     $this->creator_id=$team_creator;
    }
    
    //============================================================================
    //  Function set_setup_date() sets team creation date
    //  @param team_setup_date
    //============================================================================      
    function set_setup_date($team_setup_date) {
     $this->setup_date=$team_setup_date;
    }
    
    //============================================================================
    //  Function set_last_modify() sets team last modify
    //  @param team_setup_date
    //============================================================================      
    function set_last_modify($team_last_modify) {
     $this->last_modify=$team_last_modify;
    }
    
    //============================================================================
    //  Function strlen_utf8() returns string length in utf 8, thanx to www.php.cz
    //============================================================================

        function strlen_utf8 ($str)
        {
        $i = 0;
        $count = 0;
        $len = strlen ($str);
        while ($i < $len)
        {
        $chr = ord ($str[$i]);
        $count++;
        $i++;
        if ($i >= $len)
                break;
                
                if ($chr & 0x80)
                {
                $chr <<= 1;
                while ($chr & 0x80)
                {
                $i++;
                $chr <<= 1;
                }
                }
    }
    return $count;
    }
    
    }
    
    
?>
